<template>
  <a-modal
    title="商户管理"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="商户"
        >
          <a-tree-select :disabled="isDisabled"
                         :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                         placeholder='请选择'
                         allowClear
                         treeDefaultExpandAll
                         :treeData="treeData"
                         v-decorator="[ 'parentCode', {rules: [{ required: true, message: '请选择。。。' }]} ]"
          >
              <span style="color:#08c" slot="title" slot-scope="{key}">
                {{value}}
              </span>>
          </a-tree-select>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="代金券批次号">
          <a-input placeholder="代金券批次号" v-decorator="[ 'stockId', {rules: [{ required: true, message: '请输入。。。' }] }]"/>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="类型">
          <a-radio-group @change="onchange" buttonStyle="solid" v-decorator="[ 'type', {rules: [{ required: true, message: '请选择' }], initialValue: 1}]">
            <a-radio-button :value="1">免费优惠券</a-radio-button>
            <a-radio-button :value="2">收费优惠券</a-radio-button>
            <a-radio-button :value="3">积分兑换</a-radio-button>
            <a-radio-button :value="4">谢谢惠顾</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item v-if="isValue" :labelCol="labelCol" :wrapperCol="wrapperCol" label="金额或积分">
          <a-input placeholder="金额或积分" v-decorator="[ 'amount', {rules: [] }]"/>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序">
          <a-input placeholder="排序" v-decorator="[ 'sortNo', {rules: [] }]"/>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="每日限额(只针对购买生效)">
          <a-input placeholder="每日限额(只针对购买生效)" v-decorator="[ 'onedayQuota', {rules: [] }]"/>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="图片">
          <a-upload
            listType="picture-card"
            class="avatar-uploader"
            :showUploadList="false"
            :action="baseUrl + '/sys/upload/uploadFile'"
            :beforeUpload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" width="300px"/>
            <div v-else>
              <a-icon :type="confirmLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import pick from 'lodash.pick'
  import { selectMerchantTree } from '@/api/shop/merchant'
  import { saveOrUpdate } from '@/api/shop/coupon'

  export default {
    data () {
      return {
        baseUrl: process.env.VUE_APP_API_BASE_URL,
        id: null,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        visible: false,
        confirmLoading: false,
        isDisabled: false,
        treeData: [],
        isValue:false,
        imageUrl: '',
        fileName: null,
        form: this.$form.createForm(this)
      }
    },
    mounted () {
      const params = {'isDisable': true}
      selectMerchantTree(params).then(res => {
        if (res.code === 200) {
          this.treeData = res.result
        }
      })
    },
    methods: {
      add () {
        this.visible = true
      },
      edit (record) {
        this.id = record.id
        this.visible = true
        this.isDisabled = true
        this.imageUrl = record.couponPicUrl
        let data = Object.assign({}, record)
        if (record.type ===2 || record.type === 3) {
          this.isValue = true
          if (record.type ===2) {
            data.amount = data.amount / 100
          }
        }
        const { form: { setFieldsValue } } = this
        this.$nextTick(() => {
          const formData = pick(data, ['parentCode', 'stockId', 'type', 'amount', 'sortNo', 'onedayQuota'])
          setFieldsValue(formData)
        })
      },
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            values.id = this.id
            values.filename = this.filename
            if (values.type == 2) {
              values.amount = values.amount != undefined ? values.amount * 100 : undefined
            }
            saveOrUpdate(values).then((res) => {
              this.confirmLoading = false
              if (res.code === 200) {
                this.handleCancel()
                this.$emit('ok')
              }
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel () {
        this.visible = false
        this.isDisabled = false
        this.form.resetFields()
        this.id = null
        this.imageUrl = null
        this.filename = null
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.confirmLoading = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.imageUrl = info.file.response.fileUrl;
          this.filename = info.file.response.filename
          this.confirmLoading = false;
        }
      },
      beforeUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        // if (!isJPG) {
        //   this.$message.error('You can only upload JPG file!');
        // }
        // const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isLt2M) {
        //   this.$message.error('Image must smaller than 2MB!');
        // }
        return true;
      },
      onchange(e){
        if(e.target.value == 2 ||e.target.value == 3){
          this.isValue = true;
        }else{
          this.isValue = false;
        }
      },
    }
  }
</script>
